import { type ProColumns, ProTable, TableDropdown } from '@ant-design/pro-components';
import { Button, Modal, Switch, message } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { addRole, getRoleDetail, getRoleList, editRole, deleteRole, updateRoleStatus } from 'apis/role';
import { getOrgTree, getAppList, getMenuTree } from 'apis/common';
import Add from './Add';
import Edit from './Edit';
import AuthPerm from 'components/common/AuthPerm';

export default function ({ parentNode }):JSX.Element {
    const [addVisible, setAddVisible] = useState(false);
    const [editVisible, setEditVisible] = useState(false);
    const [messageApi] = message.useMessage();

    const [roleId, setRoleId] = useState(false);

    const dataScopeEnum = {
        1: '自定义',
        2: '本级',
        3: '本级及以上',
        4: '本级及以下',
    };

    const columns: ProColumns[] = [
        {
            title: '角色名称',
            dataIndex: 'name',
        },
        {
            title: '角色ID',
            dataIndex: 'id',
            hideInSearch: true,
        },
        {
            title: '角色标识',
            dataIndex: 'roleKey',
            hideInSearch: true,
        },
        {
            title: '状态',
            dataIndex: 'validStat',
            // filters: true,
            // onFilter: true,
            valueType: 'select',
            valueEnum: {
                1: { text: '启用' },
                0: { text: '停用' },
            },

            render: (_, record) => (
                <Switch
                    checkedChildren='启用'
                    unCheckedChildren='停用'
                    checked={record.validStat === 1}
                    onClick={() => onDisEnableStatus(record)}
                />
            ),
        },
        {
            title: '数据权限类型',
            dataIndex: 'dataScope',
            // filters: true,
            // onFilter: true,
            hideInSearch: true,
            // valueType: 'select',
            // valueEnum: {
            // 	1: { text: '自定义' },
            // 	2: { text: '本级' },
            // 	3: { text: '本级及以上' },
            // 	4: { text: '本级及以下' },
            // },

            render: (_, record) => dataScopeEnum[record.dataScope],
        },
        {
            title: '所属组织',
            key: 'organizationIdFullName',
            dataIndex: 'organizationIdFullName',
            request: async () => {
                const res = await getOrgTree({});
                return [res.organizationTree];
            },
            fieldProps: {
                // options: cascaderOptions,
                fieldNames: {
                    value: 'id',
                    label: 'name',
                },
                treeDefaultExpandAll: true,
                // showSearch: true,
                filterTreeNode: true,
                treeNodeFilterProp: 'field',
            },
            valueType: 'treeSelect',
            hideInSearch: !!parentNode,
        },
        {
            title: '操作',
            width: 180,
            key: 'option',
            valueType: 'option',
            render: (_, record) => [
                <a
                    onClick={() => {
                        setRoleId(record.id);
                        setEditVisible(true);
                    }}
                    key='link'
                >
                    修改
                </a>,
                <a onClick={() => handleDel(record.id)} key='link3'>
                    删除
                </a>,
            ],
        },
    ];

    // 表格操作
    const tableRef = useRef();
    const refresh = () => {
        tableRef.current?.reload();
    };
    const commonAction: ({
        title,
        content,
        api,
    }: {
        title: string;
        content: string;
        api: () => Promise<any>;
        successMsg: string;
    }) => void = ({ title, content, api, successMsg }) => {
        Modal.confirm({
            title,
            content,
            okText: '确定',
            cancelText: '取消',
            centered: true,
            async onOk() {
                return new Promise<void>(async (resolve, reject) => {
                    try {
                        await api();
                        messageApi.success(successMsg);
                        resolve();
                        refresh();
                    } catch (error) {
                        reject();
                    }
                });
            },
        });
    };

    const onDisEnableStatus = (record: { validStat: number; id: any }) => {
        commonAction({
            title: '提示',
            content: `确定要${record.validStat === 1 ? '停用' : '启用'}吗`,
            api: () =>
                updateRoleStatus({
                    id: record.id,
                    validStat: record.validStat === 1 ? 0 : 1,
                }),
            successMsg: `角色${record.validStat === 1 ? '已停用' : '已启用'}`,
        });
    };

    const handleDel = (id?: string) => {
        commonAction({
            title: '提示',
            content: '确定删除此角色',
            api: () =>
                deleteRole({
                    id,
                }),
            successMsg: '角色删除成功',
        });
    };

    return (
        <>
            <Add visible={addVisible} setVisible={setAddVisible} refresh={refresh} organizationId={parentNode?.id} />
            <Edit
                visible={editVisible}
                setVisible={setEditVisible}
                refresh={refresh}
                roleId={roleId}
                organizationId={parentNode?.id}
            />
            <ProTable
                params={{
                    organizationId: parentNode?.id,
                }}
                actionRef={tableRef}
                columns={columns}
                request={async (params) => {
                    // 表单搜索项会从 params 传入，传递给后端接口。
                    console.log(params);
                    const res = await getRoleList({
                        ...params,
                        ...{
                            pageNumber: params.current,
                            current: undefined,
                            organizationId: params.organizationIdFullName,
                        },
                    });
                    console.log(res);
                    return Promise.resolve({
                        data: res.recordDatas,
                        total: res.totalRow,
                        success: true,
                    });
                }}
                rowKey='id'
                pagination={{
                    showQuickJumper: true,
                }}
                search={{
                    layout: 'vertical',
                    defaultCollapsed: false,
                }}
                dateFormatter='string'
                toolBarRender={() => [
                        <Button type='primary' key='primary' onClick={() => setAddVisible(true)}>
                            新建
                        </Button>

                ]}
                scroll={{
                    y: '80vh',
                }}
            />
        </>
    );
}
